<template>
    <div class="form">
        <a-form-model ref="ruleForm" :model="form" :rules="rules" :label-col="{ span: 5 }" :wrapper-col="{ span: 18 }">
            <h2>需求信息</h2>
            <a-form-model-item label="标题" prop="title">
                <a-input
                    v-model="form.title"
                    :maxLength="30"
                    placeholder="请输入标题"
                    v-if="!isDetail"
                    :disabled="isDetail"
                ></a-input>
                <p class="form-detail-text" v-else>{{ form.title }}</p>
            </a-form-model-item>
            <a-form-model-item label="区域" prop="areaCode">
                <city-cascader v-model="form.areaCode" :disabled="isDetail" :chooseEvery="false"></city-cascader>
            </a-form-model-item>
            <a-form-model-item label="需求类型" prop="multipleType">
                <el-cascader
                    v-model="form.multipleType"
                    :options="treeData"
                    placeholder="请选择需求类型"
                    size="small"
                    :disabled="isDetail"
                    clearable
                    :props="{ label: 'name', value: 'id', children: 'children', multiple: true }"
                ></el-cascader>
                <p class="multiple-tip">多选,最多允许选择10个。如超出10个则只会保存前10个选项。</p>
            </a-form-model-item>
            <a-form-model-item label="图片" prop="pictureList" class="img-input">
                <p class="size">单张最大6M，最多上传6张</p>
                <custom-upload
                    v-if="!isDetail"
                    :typeList="['image/jpeg', 'image/png', 'image/bmp']"
                    path="need-manage/img"
                    :max="6"
                    :fileSize="6"
                    btnText="上传图片"
                    v-model="form.pictureList"
                ></custom-upload>
                <div class="img-box" v-else>
                    <template v-for="(item, index) in form.pictureList">
                        <img
                            :src="$staticUrl + '/' + item"
                            alt=""
                            :key="index"
                            @click="showPicturesModal(item, form.pictureList)"
                        />
                    </template>
                </div>
            </a-form-model-item>
            <a-form-model-item label="需求介绍" prop="introduction" class="description-form-item">
                <a-textarea
                    v-model="form.introduction"
                    :disabled="isDetail"
                    placeholder="请输入需求介绍"
                    :rows="4"
                    :maxLength="500"
                />
                <span class="length-tips">{{ form.introduction ? form.introduction.length : 0 }}/500</span>
            </a-form-model-item>
            <h2>发布人信息</h2>
            <a-form-model-item label="姓名" prop="personnelName">
                <a-input
                    v-model="form.personnelName"
                    :disabled="isDetail || isService"
                    placeholder="请输入姓名"
                    :maxLength="10"
                ></a-input>
            </a-form-model-item>
            <a-form-model-item label="手机号" prop="phone">
                <a-input
                    v-model="form.phone"
                    :maxLength="11"
                    placeholder="请输入手机号"
                    :disabled="isDetail || isService"
                ></a-input>
            </a-form-model-item>
            <h2>企业信息</h2>
            <a-form-model-item label="企业名称" prop="enterName">
                <a-input
                    v-model="form.enterName"
                    :maxLength="50"
                    placeholder="请输入企业名称"
                    v-if="!isDetail"
                    :disabled="isDetail || isService"
                ></a-input>
                <p class="form-detail-text" v-else>{{ form.enterName }}</p>
            </a-form-model-item>
            <a-form-model-item label="企业规模">
                <a-select v-model="form.enterScale" :disabled="isDetail || isService" placeholder="请选择企业规模">
                    <template v-for="(item, index) in enterScaleList">
                        <a-select-option :value="item.id" :key="index">{{ item.name }}</a-select-option>
                    </template>
                </a-select>
            </a-form-model-item>
            <a-form-model-item label="企业年营收规模" prop="enterIncome">
                <a-select
                    v-model="form.enterIncome"
                    :disabled="isDetail || isService"
                    :allowClear="true"
                    placeholder="请选择企业年营收规模"
                >
                    <template v-for="(item, index) in enterIncomeList">
                        <a-select-option :value="item.id" :key="index">{{ item.name }}</a-select-option>
                    </template>
                </a-select>
            </a-form-model-item>
            <a-form-model-item v-if="!isDetail && isService" prop="privacy" label=" " class="check-privacy">
                <a-checkbox v-model="form.privacy">
                    我已阅读并同意<span class="link" @click="toShowRules">《发布规则》</span>
                </a-checkbox>
            </a-form-model-item>
            <a-form-model-item v-if="!isDetail">
                <template v-if="isService">
                    <a-button @click="goBack" class="next-btn">取消</a-button>
                    <a-button @click="submit()">提交需求信息</a-button>
                </template>
                <template v-else>
                    <a-button @click="submitForm" class="next-btn">保存</a-button>
                    <a-button @click="submit('release')">保存并发布</a-button>
                </template>
            </a-form-model-item>
        </a-form-model>
    </div>
</template>

<script>
import CityCascader from '~/components/city-cascader'
import { showRules } from '~/components/need-manage/publishing-rules'

export default {
    // 服务需求
    name: 'ServiceNeed',
    components: {
        CityCascader
    },
    data () {
        const checkTel = (rule, value, callback) => {
            // if (!(/^1[3456789]\d{9}$/.test(value))) {
            if (value.length > 11) {
                callback(new Error('请输入正确的联系电话'))
            } else {
                callback()
            }
        }
        const checkPrivacy = (rule, value, callback) => {
            if (value) {
                callback()
            } else {
                callback(new Error('请阅读并同意发布规则'))
            }
        }
        return {
            form: {
                // 标题
                title: '',
                // 区域
                areaCode: '',
                // 需求类型
                multipleType: [],
                // 图片
                pictureList: [],
                // 介绍
                introduction: '',
                // 姓名
                personnelName: '',
                // 手机号
                phone: '',
                // 公司名称
                enterName: '',
                // 公司规模
                enterScale: undefined,
                enterScaleName: '',
                // 公司规模其他
                enterScaleRemark: '',
                // 上一年营收规模
                enterIncome: undefined,
                privacy: false
            },
            treeData: [],
            enterScaleList: [
                {
                    id: 1,
                    name: '0-20人'
                },
                {
                    id: 2,
                    name: '20-100人'
                },
                {
                    id: 3,
                    name: '100-300人'
                },
                {
                    id: 4,
                    name: '300-1000人'
                },
                {
                    id: 5,
                    name: '1000人以上'
                }
            ],
            enterIncomeList: [
                {
                    id: 1,
                    name: '0-1000万元'
                },
                {
                    id: 2,
                    name: '1000万-5000万元'
                },
                {
                    id: 3,
                    name: '5000万-1亿元'
                },
                {
                    id: 4,
                    name: '1亿元以上'
                }
            ],
            rules: {
                title: [
                    { required: true, message: '请输入标题', trigger: 'blur' },
                    { max: 30, message: '最多可输入30个字符', trigger: 'change' }
                ],
                areaCode: [{ required: true, message: '请选择区域', trigger: 'change' }],
                multipleType: [{ required: true, message: '请选择需求类型', trigger: 'change' }],
                introduction: [{ required: true, message: '请输入介绍', trigger: 'change' }],
                personnelName: [{ required: true, message: '请输入姓名', trigger: 'change' }],
                phone: [
                    { required: true, message: '请输入手机号', trigger: 'change' },
                    { validator: checkTel, trigger: 'change' }
                ],
                enterName: [{ required: true, message: '请输入企业名称', trigger: 'blur' }],
                // enterScale: [{ required: true, message: '请选择企业规模', trigger: 'change' }],
                privacy: [{ validator: checkPrivacy }]
            }
        }
    },
    computed: {
        isDetail () {
            return !!this.$route.query.d
        },
        isService () {
            return this.$route.path.includes('need-manage-service')
        }
    },
    created () {
        if (this.$route.query.id) {
            this.getInfo()
        }
        this.getTree()
        if (this.$route.path.includes('need-manage-service') && !this.$route.query.id) {
            this.getCompanyInfo()
        }
    },
    mounted () {},
    methods: {
        async getCompanyInfo () {
            const res = await this.$ApiServer['company/mange/detail']()
            if (res.code === 200) {
                const { name, income, employeeScale } = res.data
                this.form.personnelName = this.$store.state.user.userInfo.name
                this.form.phone = this.$store.state.user.userInfo.tel
                this.form.enterName = name
                this.form.enterIncome = this.enterIncomeList.filter(item => item.name === income)[0].id
                this.form.enterScale = this.enterScaleList.filter(item => item.name === employeeScale)[0].id
            }
        },
        toShowRules () {
            this.form.privacy = !this.form.privacy
            showRules({
                sure: (vm) => {
                    this.form.privacy = true
                    vm.close()
                }
            })
        },
        goBack () {
            this.$router.go(-1)
        },
        async getTree (serviceKindId) {
            const res = await this.$ApiServer['operationConfig/getTree']()
            if (res.code === 200) {
                const add = (list) => {
                    list.forEach((item) => {
                        item.scopedSlots = { title: 'custom' }
                        if (item.children && item.children.length) {
                            item.children = add(item.children)
                        } else {
                            item.children = []
                        }
                    })
                    return list
                }
                this.treeData = add(res.data)
                const filterStatus = (list) => {
                    return list.filter((item) => {
                        if (item.children) {
                            item.children = filterStatus(item.children)
                        }
                        return item.status
                    })
                }
                this.treeData = filterStatus(this.treeData)
                this.treeData.forEach((item) => {
                    if (item.children) {
                        item.children.forEach((it) => {
                            delete it.children
                        })
                    }
                })
                if (serviceKindId) {
                    let one, tow, three
                    const list = this.treeData
                    for (let i = 0; i < list.length; i++) {
                        one = list[i].id
                        if (list[i].id === serviceKindId) {
                            break
                        } else if (list[i].children) {
                            const list2 = list[i].children
                            let flag1 = true
                            for (let j = 0; j < list2.length; j++) {
                                tow = list2[j].id
                                if (list2[j].id === serviceKindId) {
                                    flag1 = false
                                    break
                                } else if (list2[j].children) {
                                    const list3 = list2[j].children
                                    let flag2 = true
                                    for (let q = 0; q < list3.length; q++) {
                                        three = list3[q].id
                                        if (list3[q].id === serviceKindId) {
                                            flag2 = false
                                            break
                                        }
                                    }
                                    if (!flag2) {
                                        flag1 = false
                                        break
                                    }
                                }
                            }
                            if (!flag1) break
                        }
                    }
                    this.form.multipleType = [one, tow, three].filter(item => item)
                }
            }
        },
        async submitForm () {
            const url = this.$route.path.includes('need-manage-service')
                ? 'need/updateService/service'
                : 'need/update/service'
            const res = await this.$ApiServer[url]({
                areaCode: this.form.areaCode || null,
                enterIncome: this.form.enterIncome || null,
                enterName: this.form.enterName || null,
                enterScale: this.form.enterScale || null,
                personnelName: this.form.personnelName || null,
                phone: this.form.phone || null,
                introduction: this.form.introduction || null,
                id: this.$route.query.id || null,
                pictureList: this.form.pictureList.length ? this.form.pictureList : null,
                suppInformList: [],
                title: this.form.title || null,
                saveType: 1,
                multipleType:
                    this.form.multipleType
                        .filter((item, index) => index < 10)
                        .map(item => item[item.length - 1])
                        .join(',') || null,
                type: 0,
                firstKind:
                    this.form.multipleType
                        .filter((item, index) => index < 10)
                        .map(item => item[0])
                        .join(',') || null
            })
            if (res.code === 200) {
                this.$message.success(res.message)
                this.$router.go(-1)
            } else {
                this.$message.error(res.message)
            }
        },
        submit (type) {
            this.$refs.ruleForm.validate(async (valid) => {
                if (valid) {
                    const url = this.$route.path.includes('need-manage-service')
                        ? 'need/updateService/service'
                        : 'need/update/service'
                    const res = await this.$ApiServer[url]({
                        areaCode: this.form.areaCode,
                        enterIncome: this.form.enterIncome,
                        enterName: this.form.enterName,
                        enterScale: this.form.enterScale,
                        personnelName: this.form.personnelName,
                        phone: this.form.phone,
                        introduction: this.form.introduction,
                        id: this.$route.query.id || '',
                        pictureList: this.form.pictureList,
                        suppInformList: [],
                        title: this.form.title,
                        saveType: type === 'release' ? 2 : 1,
                        multipleType: this.form.multipleType
                            .filter((item, index) => index < 10)
                            .map(item => item[item.length - 1])
                            .join(','),
                        type: 0,
                        firstKind: this.form.multipleType
                            .filter((item, index) => index < 10)
                            .map(item => item[0])
                            .join(',')
                    })
                    if (res.code === 200) {
                        this.$message.success(res.message)
                        this.$router.go(-1)
                    } else {
                        this.$message.error(res.message)
                    }
                }
            })
        },
        async getInfo () {
            const res = await this.$ApiServer['need/getInfo/service']({
                id: this.$route.query.id
            })
            if (res.code === 200) {
                this.form = {
                    ...res.data,
                    enterScale: res.data.enterScale ? Number(res.data.enterScale) : undefined,
                    enterIncome: res.data.enterIncome ? Number(res.data.enterIncome) : undefined,
                    multipleType: []
                }
                this.form.areaCode = res.data.areaCode || ''
                this.form.pictureList = res.data.pictureList || []
                this.form.enterScaleRemark = res.data.suppInformList ? res.data.suppInformList[0] || '' : ''
                this.form.multipleType = res.data.multipleTypeList
                    ? res.data.multipleTypeList.map(item => item.split('/'))
                    : []
                this.form.privacy = true
                this.$emit('getAudit', res.data.rejectEvent)
            } else {
                this.$message.error(res.message)
            }
        },
        // 预览大图
        showPicturesModal (url, urls) {
            if (urls.length) {
                this.$picturesModal({
                    url,
                    urls
                })
            }
        }
    }
}
</script>

<style scoped lang="less">
.form {
    background: #fff;
    padding: 10px calc(100% - 600px) 40px 20px;
    position: relative;
    h2 {
        font-size: 16px;
        line-height: 22px;
        margin-bottom: 10px;
    }
    .next-btn {
        margin-left: 121px;
        margin-right: 10px;
    }
    .multiple-tip {
        font-size: 12px;
        font-weight: 400;
        line-height: 17px;
        color: #666;
        margin: 0;
    }
    .img-input {
        .size {
            font-size: 12px;
            font-weight: 400;
            line-height: 17px;
            color: @primary-color;
            margin-bottom: 6px;
            padding-top: 11px;
        }
        ::v-deep {
            .ant-upload-select {
                width: 200px;
                height: 150px;
                background: #fff;
                border: 1px solid #d4d4d4;
                &:hover {
                    border: 1px solid @primary-color;
                    .anticon {
                        color: @primary-color;
                    }
                    .ant-upload-text {
                        color: @primary-color;
                    }
                }
                .anticon {
                    font-size: 42px;
                    color: #666;
                }
                .ant-upload-text {
                    font-size: 14px;
                    color: #666;
                }
            }
            .ant-upload-list-picture-card-container {
                width: 200px;
                height: 150px;
            }
            .ant-upload-list-picture-card .ant-upload-list-item {
                width: 200px;
                height: 150px;
            }
            .ant-upload-picture-card-wrapper {
                width: 630px;
            }
        }
    }
    .check-privacy {
        .link {
            color: #009944;
            cursor: pointer;
        }
    }
}
.img-box {
    img {
        width: 150px;
        height: 150px;
        margin-right: 10px;
        cursor: pointer;
        object-fit: contain;
    }
}
</style>
